package com.hb.znpt.viewmodel;

import android.app.Application;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.lifecycle.MutableLiveData;

import com.hb.znpt.bean.CropsBean;
import com.hb.znpt.model.LandAddModel;
import com.hb.znpt.utils.ObjectWriter;
import com.rxjava.rxlife.RxLife;
import com.unitlib.base.base.BaseViewModel;
import com.unitlib.base.utils.ToastUtils;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;

public class LandAddViewModel extends BaseViewModel<LandAddModel> {

    public ObservableField<String> name = new ObservableField<>("");
    public ObservableField<String> area = new ObservableField<>("");

    private String deptid = null;

    public MutableLiveData<List<CropsBean>> cropClick = new MutableLiveData<>();

    public LandAddViewModel(@NonNull Application application) {
        super(application);
        model = new LandAddModel();
    }

    public void crop(View view) {
        List<CropsBean> beans = (List<CropsBean>) ObjectWriter.read(context, "nzwlist");
        cropClick.setValue(beans);
    }

    public void submit(View view) {
        if (isEmpty()) {
            model.send(name.get(), area.get(), deptid)
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(disposable -> {
                        showDialog();
                    })
                    .doFinally(() -> {
                        dismissDialog();
                    })
                    .as(RxLife.as(owner))
                    .subscribe(been -> {
                        finish();
                        ToastUtils.showShort("提交成功！");
                    }, error -> {
                        ToastUtils.showShort(error.getMessage());
                    });
        }
    }

    private boolean isEmpty() {
        if (TextUtils.isEmpty(area.get())) {
            ToastUtils.showShort("请输入作物面积！");
            return false;
        }
        if (TextUtils.isEmpty(name.get())) {
            ToastUtils.showShort("请选择作物种类！");
            return false;
        }
        return true;
    }

    public String getDeptid() {
        return deptid;
    }

    public void setDeptid(String deptid) {
        this.deptid = deptid;
    }
}
